package com.governtalk.backend.controller;

import com.governtalk.backend.entity.User;
import com.governtalk.backend.repository.UserRepository;
// import io.jsonwebtoken.Jwts;
// import io.jsonwebtoken.SignatureAlgorithm;
// import io.jsonwebtoken.security.Keys;
// import javax.crypto.SecretKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private UserRepository userRepository;
    
    // @Value("${jwt.secret}")
    // private String jwtSecret;
    
    // @Value("${jwt.expiration}")
    // private Long jwtExpiration;
    
    private BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    
    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody Map<String, String> loginRequest) {
        String username = loginRequest.get("username");
        String password = loginRequest.get("password");
        
        Optional<User> userOpt = userRepository.findByUsername(username);
        if (userOpt.isPresent()) {
            User user = userOpt.get();
            // 使用BCrypt验证密码
            if (passwordEncoder.matches(password, user.getPassword()) && user.getIsEnabled()) {
                String token = generateToken(user);
                
                Map<String, Object> response = new HashMap<>();
                response.put("token", token);
                Map<String, Object> userInfo = new HashMap<>();
                userInfo.put("id", user.getId());
                userInfo.put("username", user.getUsername());
                userInfo.put("email", user.getEmail());
                userInfo.put("nickname", user.getNickname());
                userInfo.put("avatar", user.getAvatarUrl());
                response.put("user", userInfo);
                response.put("message", "Login successful");
                
                return ResponseEntity.ok(response);
            }
        }
        
        Map<String, Object> response = new HashMap<>();
        response.put("error", "Invalid username or password");
        return ResponseEntity.badRequest().body(response);
    }
    
    @PostMapping("/register")
    public ResponseEntity<Map<String, Object>> register(@RequestBody Map<String, String> registerRequest) {
        String username = registerRequest.get("username");
        String password = registerRequest.get("password");
        String email = registerRequest.get("email");
        String nickname = registerRequest.get("nickname");
        
        // 检查用户名是否已存在
        if (userRepository.existsByUsername(username)) {
            Map<String, Object> response = new HashMap<>();
            response.put("error", "Username already exists");
            return ResponseEntity.badRequest().body(response);
        }
        
        // 检查邮箱是否已存在
        if (userRepository.existsByEmail(email)) {
            Map<String, Object> response = new HashMap<>();
            response.put("error", "Email already exists");
            return ResponseEntity.badRequest().body(response);
        }
        
        // 创建新用户
        User user = new User();
        user.setUsername(username);
        user.setPassword(passwordEncoder.encode(password)); // 使用BCrypt加密密码
        user.setEmail(email);
        user.setNickname(nickname);
        user.setIsEnabled(true);
        user.setIsLocked(false);
        user.setCreatedAt(java.time.LocalDateTime.now());
        user.setUpdatedAt(java.time.LocalDateTime.now());
        
        User savedUser = userRepository.save(user);
        
        Map<String, Object> response = new HashMap<>();
        response.put("message", "Registration successful");
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("id", savedUser.getId());
        userInfo.put("username", savedUser.getUsername());
        userInfo.put("email", savedUser.getEmail());
        userInfo.put("nickname", savedUser.getNickname());
        response.put("user", userInfo);
        
        return ResponseEntity.ok(response);
    }
    
    private String generateToken(User user) {
        // 临时使用简单的token，避免JWT问题
        return "token_" + user.getUsername() + "_" + System.currentTimeMillis();
    }
}